import 'dart:io';

import 'package:args/args.dart';

class ShellArg {
  late bool json2bean;

  String? projectDir;

  String? beanName;

  String? libDir;

  ///the dir for search dartBean to gen dart part
  String? searchDir;

  static ShellArg parse(List<String> args) {
    return _from(_initParser(args));
  }

  static ShellArg _from(ArgResults arg) => ShellArg()
    ..json2bean = arg['json2bean']
    ..projectDir = arg['projectDir']
    ..beanName = arg['beanName']
    ..libDir = arg['libDir']
    ..searchDir = arg['searchDir'];

  static ArgResults _initParser(List<String> args) {
    final parser = ArgParser()
      ..addFlag('json2bean', defaultsTo: false, help: r'Arguments:--json2bean --beanName $Prompt$')
      ..addOption('projectDir', help: "project root dir which contains 'pubspec.yaml'")
      ..addOption('beanName', help: r"""
bean name(include path relative to libDir) for json2bean,
eg:'data/user_info' -> lib/data/user_info.dart
root bean -> class UserInfo{}
      """)
      ..addOption('libDir', defaultsTo: 'lib', help: 'project lib dir relative to projectDir')
      ..addOption('searchDir', help: 'the dir for searching dartBean to gen dart part');
    return parser.parse(args);
  }

  void checkArgs() {
    if (projectDir == null) {
      final yaml = File('./pubspec.yaml');
      if (yaml.existsSync()) projectDir = '.'; //working dir
    }
    if (projectDir == null) {
      throw r'need parameters [projectDir]'
          r'External tools settings'
          r'Arguments:--projectDir $ProjectFileDir$'
          r'or working directory:$ProjectFileDir$';
    }

    if (json2bean && beanName == null) {
      throw r"""
need parameters [beanName]
External tools settings
Arguments:--json2bean --beanName $Prompt$
""";
    }
  }
}
